import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:verse_systems/pages/authentication/authentication_control.dart';
import 'package:verse_systems/res/colors.dart';
import 'package:verse_systems/res/gaps.dart';
import 'package:verse_systems/utils/image_utils.dart';
import 'package:verse_systems/widgets/drawer_appbar.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:verse_systems/widgets/sp_button.dart';

class Authentication extends StatefulWidget {
  const Authentication({super.key});

  @override
  State<Authentication> createState() => _AuthenticationState();
}

class _AuthenticationState extends State<Authentication> {
  final control = Get.find<AuthenticationControl>();
  final state = Get.find<AuthenticationControl>().state;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colours.system_background_color,
      appBar: DrawerAppbar(
        title: 'identity_authorization'.tr,
      ),
      body: GetBuilder<AuthenticationControl>(
          init: control,
          builder: (_) {
            return GestureDetector(
                onTap: () {
                  FocusScope.of(context).unfocus();
                },
                child: SingleChildScrollView(
                  child: Column(
                    children: [
                      _information,
                      _presentation,
                      _inforconfirm,
                      _agreement,
                      _next,
                      _nextLine
                    ],
                  ),
                ));
          }),
    );
  }

  Widget get _nextLine {
    return SizedBox(height: 30.w);
  }

  Widget get _next {
    return SizedBox(
      width: 310.w,
      child: SPButton(
        minHeight: 50.w,
        fontSize: 13.sp,
        text: "next".tr,
        textColor: Colours.app_main_color,
        backgroundColor: Colours.app_main_background_color,
        radius: 25.w,
        onPressed: control.handleNext,
      ),
    );
  }

  Widget get _agreement {
    return Container(
        margin: EdgeInsets.fromLTRB(0, 55.w, 0, 25.w),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            SizedBox(
              width: 30.w,
              height: 30.w,
              child: Obx(() {
                return Checkbox(
                    value: state.agreementIsChecked,
                    activeColor: Colours.app_main_background_color,
                    checkColor: Colours.app_main_color,
                    hoverColor: Colours.app_main_background_color,
                    shape: const CircleBorder(),
                    onChanged: (v) {
                      if (v == true) {}
                      state.agreementIsChecked = v ?? true;
                    });
              }),
            ),
            Gaps.hGap4,
            RichText(
                text: TextSpan(children: [
              TextSpan(
                text: 'read_and_agreed'.tr,
                style: TextStyle(
                  color: Colours.color_99,
                  fontSize: 12.sp,
                ),
                recognizer: TapGestureRecognizer()
                  ..onTap = () {
                    state.agreementIsChecked = !state.agreementIsChecked;
                  },
              ),
              TextSpan(
                text: 'information_authorization'.tr,
                style: TextStyle(
                  color: Colours.blue_text_color,
                  fontSize: 12.sp,
                  decoration: TextDecoration.underline,
                ),
                recognizer: TapGestureRecognizer()
                  ..onTap = control.handleProtocol,
              ),
            ]))
          ],
        ));
  }

  Widget get _inforconfirm {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 24.w),
      width: MediaQuery.of(context).size.width,
      color: Colours.app_main_color,
      child: Column(
        children: [
          _inforTextFeild(
              name: "real_name".tr,
              widget: _textField(
                  placeholder: 'please_enter_name'.tr,
                  controller: control.name)),
          _inforTextFeild(
              name: "real_name_number".tr,
              widget: _textField(
                  placeholder: 'please_enter_id_number'.tr,
                  controller: control.idNumber)),
          _inforTextFeild(
              name: "性别",
              widget: InkWell(
                  onTap: control.handleGenderInfo,
                  child: TextField(
                    enabled: false,
                    keyboardType: TextInputType.text,
                    controller: control.gender,
                    textAlign: TextAlign.right, //文本对齐方式
                    style: TextStyle(
                      fontSize: 15.sp,
                      color: Colours.app_black_text_color,
                    ),
                    decoration: InputDecoration(
                        contentPadding: EdgeInsets.symmetric(vertical: 5.w),
                        border: InputBorder.none,
                        hintText: 'please_select_gender'.tr,
                        counterText: '',
                        hintStyle: TextStyle(
                          fontSize: 15.sp,
                          color: Colours.app_text_color,
                        )),
                    showCursor: true,
                    cursorColor: Colours.app_main_background_color,
                    onChanged: (v) {},
                  )))
        ],
      ),
    );
  }

  Widget _textField({String? placeholder, TextEditingController? controller}) {
    return TextField(
      maxLines: 1,
      maxLength: 18,
      keyboardType: TextInputType.text,
      controller: controller,
      textAlign: TextAlign.right, //文本对齐方式
      style: TextStyle(
        fontSize: 15.sp,
        color: Colours.app_black_text_color,
      ),
      decoration: InputDecoration(
          contentPadding: EdgeInsets.symmetric(vertical: 5.w),
          border: InputBorder.none,
          hintText: placeholder,
          counterText: '',
          hintStyle: TextStyle(
            fontSize: 15.sp,
          )),
      showCursor: true,
      cursorColor: Colours.app_main_background_color,
      onChanged: (v) {},
    );
  }

  Widget _inforTextFeild({String? name, required Widget widget}) {
    return Column(
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Row(children: [
              Text("*",
                  style: TextStyle(
                    color: Colours.app_text_red_color,
                    fontSize: 16.sp,
                  )),
              Text(
                "$name",
                style: TextStyle(
                  color: Colours.app_black_text_color,
                  fontSize: 16.sp,
                ),
              )
            ]),
            SizedBox(width: 5.w),
            Expanded(child: widget)
          ],
        ),
        Container(
          height: 1.w,
          color: Colours.app_text_line_color,
        )
      ],
    );
  }

  Widget get _information {
    return Container(
        width: MediaQuery.of(context).size.width,
        color: Colours.app_main_color,
        padding: EdgeInsets.symmetric(horizontal: 24.w),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            SizedBox(height: 24.w),
            Row(
              children: [
                Image.asset(
                  ImageUtils.getImgPath("authentication"),
                  fit: BoxFit.fill,
                  width: 38.w,
                  height: 30.w,
                ),
                Text(
                  "identity_authorization".tr,
                  style: TextStyle(
                      color: Colours.app_black_text_color,
                      fontSize: 24.sp,
                      fontWeight: FontWeight.w600),
                ),
              ],
            ),
            Container(
                margin: EdgeInsets.fromLTRB(0, 14.w, 0, 12.w),
                child: Text(
                  state.notice_verify,
                  style: TextStyle(
                    color: Colours.app_text_color,
                    fontSize: 12.sp,
                  ),
                )),
            GestureDetector(
                onTap: control.jumpToAuthenPoint,
                child: Text(
                  "problem_id_card_recognition".tr,
                  style: TextStyle(
                    color: Colours.app_text_bluer_color,
                    fontSize: 12.sp,
                    decoration: TextDecoration.underline,
                  ),
                )),
            Container(
              margin: EdgeInsets.fromLTRB(0, 26.w, 0, 36.w),
              child: Wrap(
                spacing: 15.w,
                runSpacing: 25.w,
                children: _idCard,
              ),
            )
          ],
        ));
  }

  Widget get _presentation {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 23.w),
      height: 31.w,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            "confirm_information".tr,
            style: TextStyle(
              color: Colours.app_text_color,
              fontSize: 12.sp,
            ),
          ),
          Text(
            "confirm_information_not_amend".tr,
            style: TextStyle(
              color: Colours.app_text_red_color,
              fontSize: 12.sp,
            ),
          ),
        ],
      ),
    );
  }



  List<Map> get _cardList {
    if (state.openOcr) {
      return [
        {
          "title": "picture_person_id".tr,
          "image": "id-card-front",
          "url": state.positive,
          "path": ImageUtils.getImgPath("positive_photo"),
        },
        {
          "title": "picture_of_back".tr,
          "image": "id-card-reverse",
          "url": state.reverse,
          "path": ImageUtils.getImgPath("reverse_photo"),
        },
        {
          "title": "click_face".tr,
          "image": "ocr-image",
          "url": state.face,
          "path": ImageUtils.getImgPath("face_photo"),
        },
      ];
    } else {
      return [
        {
          "title": "picture_person_id".tr,
          "image": "id-card-front",
          "url": state.positive,
          "path": ImageUtils.getImgPath("positive_photo"),
        },
        {
          "title": "picture_of_back".tr,
          "image": "id-card-reverse",
          "url": state.reverse,
          "path": ImageUtils.getImgPath("reverse_photo"),
        },
      ];
    }
  }

  List<Widget> get _idCard {
    return _cardList.map((val) {
      return InkWell(
          onTap: () {
            control.jumpOpenCamera(image: val["image"].toString());
          },
          child: SizedBox(
              width: (MediaQuery.of(context).size.width - 65.w) / 2,
              height: 130.w,
              child: (val["url"] == "")
                  ? Image.asset(
                      val["path"].toString(),
                      fit: BoxFit.fill,
                      width: 140.w,
                      height: 130.w,
                    )
                  : Stack(
                      children: [
                        CachedNetworkImage(
                          fit: BoxFit.fill,
                          width: (MediaQuery.of(context).size.width - 65.w) / 2,
                          height: 106.w,
                          imageUrl: val["url"].toString(),
                          placeholder: (context, url) => Transform.scale(
                            scale: 0.3,
                            child: const CircularProgressIndicator(
                              color: Colours.app_main_background_color,
                            ),
                          ),
                          errorWidget: (context, url, error) =>
                              const Icon(Icons.error),
                        ),
                        Positioned(
                            bottom: 0,
                            right: 0,
                            child: Container(
                              alignment: Alignment.center,
                              width:
                                  (MediaQuery.of(context).size.width - 65.w) /
                                      2,
                              height: 24.w,
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.only(
                                    bottomLeft: Radius.circular(6.w),
                                    bottomRight: Radius.circular(6.w)),
                                color: Colours.app_main_text_color,
                              ),
                              child: Text(val["title"].toString(),
                                  style: TextStyle(
                                    color: Colours.app_main_color,
                                    fontSize: 13.sp,
                                  )),
                            )),
                        Positioned(
                            bottom: 60,
                            right: 60,
                            child: Image.asset(
                              ImageUtils.getImgPath("success"),
                              fit: BoxFit.fill,
                              width: 30.w,
                              height: 30.w,
                            )),
                      ],
                    )));
    }).toList();
  }
}
